/**
 * @file ShellContextImpl.java
 * Projet eCOM 2010 (Miage Descartes)
 * @author Doido Sébastien
 * @version 2
 * @brief Shell : Gestion du contexte du shell
 */
package ecom.shell;

import ecom.shell.OutputCommandImpl.Outputs;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Iterator;

class ShellContextImpl implements ShellContext {
	private Map _commands;
    private Map _commandsHelp;
    private Map _environnementVariables;
	
	public ShellContextImpl(Map commands, Map commandsHelp){
		_commands=commands;
        _commandsHelp=commandsHelp;
		_environnementVariables=new TreeMap();
	}
	
	public synchronized ShellCommand[] getCommands() {
		ShellCommand[] cmds=new ShellCommand[_commands.size()];
		Iterator iterator=_commands.values().iterator();
		for(int i=0;iterator.hasNext(); i++) {
			cmds[i]=(ShellCommand)iterator.next();	
		}
		return cmds;
	}

    public synchronized ShellCommand[] getCommandsHelp() {
		ShellCommand[] cmds=new ShellCommand[_commandsHelp.size()];
		Iterator iterator=_commandsHelp.values().iterator();
		for(int i=0;iterator.hasNext(); i++) {
			cmds[i]=(ShellCommand)iterator.next();
		}
		return cmds;
	}
	
	public Object getVar(String key){
		return _environnementVariables.get(key);
	}
	public Set getVarNames(){
		return _environnementVariables.keySet();
	}
	public void setVar(String key, Object value){
		_environnementVariables.put(key,value);
	}
	public Object unsetVar(String key){
		return _environnementVariables.remove(key);
	}
    public String returnCode(String msg, ShellConstantes.RESULT_ACTION result ) {
        StringBuffer res = new StringBuffer();
        Outputs currentOutput = (Outputs) getVar("output");
        if (currentOutput.equals(Outputs.XML)) {
            res.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "\n");
            res.append("<action result=\""+result+"\">" + "\n");
            res.append("\t" + msg + "\n");
            res.append("</action>" + "\n");
        }else if (currentOutput.equals(Outputs.TEXT)) {
            res.append("[" + result + "] " + msg + "\n");
        } else {
            res.append("Output not implemented");
        }
        return res.toString();
    }
}

